package com.datareport.data.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.datareport.data.dto.ResultDTO;
import com.datareport.data.entity.ErrorInfo;
import com.datareport.data.service.ErrorInfoService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author DataReport
 * @since 2021-11-22
 */
@RestController
public class ErrorInfoController {


    @Autowired
    ErrorInfoService errorInfoService;

    /**
     * @param list 错误类别列表
     * @return
     */
    @ApiOperation("校验功能")
    @PostMapping("/check")
    public ResultDTO check(@RequestBody List<String> list) {
        errorInfoService.check(list);

        return ResultDTO.okOf();
    }

    /**
     * @param pageNum  请求的数据页数
     * @param pageSize 请求数据条数
     * @return
     */
    @ApiOperation("查询所有信息接口")
    @GetMapping("/ErrorInfo/selectAll")
    public IPage<ErrorInfo> selectErrorInfoPage(@RequestParam("pageNum") Integer pageNum,
                                                @RequestParam("pageSize") Integer pageSize) {

        Page<ErrorInfo> pastPage = errorInfoService.selectAll(pageNum, pageSize);

        return pastPage;
    }


    /**
     * Excel文件导出接口
     * @param response
     * @throws IOException
     */
    @ApiOperation("Excel文件导出接口")
    @GetMapping("/export")
    public void exportFile(HttpServletResponse response) throws IOException {

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("错误信息导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        int count = errorInfoService.count();
        //数据量少于10万
        if (count < 100000) {

            List<ErrorInfo> list = errorInfoService.list();

            try {

                // 这里需要设置不关闭流
                EasyExcel.write(response.getOutputStream(), ErrorInfo.class).autoCloseStream(Boolean.FALSE).sheet("信息")
                        .doWrite(list);
            } catch (Exception e) {
                // 重置response
                response.reset();
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                Map<String, String> map = new HashMap<>();
                map.put("status", "failure");
                map.put("message", "下载文件失败" + e.getMessage());
                response.getWriter().println(JSON.toJSONString(map));
            }
        }
        //数据量大于10万，分页导出
        else {
            //每页多少条数据
            int max = 10000;

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();

            try {
                for (int i = 0; i < (count / max) + 1; i++) {

                    Page<ErrorInfo> page=errorInfoService.selectAll(i+1,max);

                    List<ErrorInfo> records = page.getRecords();

                    WriteSheet writeSheet = EasyExcel.writerSheet(i, "信息" + (i + 1)).head(ErrorInfo.class)
                            .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();

                    excelWriter.write(records, writeSheet);
                }

                excelWriter.finish();
            } catch (Exception exception) {
                // 重置response
                response.reset();
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                Map<String, String> map = new HashMap<>();
                map.put("status", "failure");
                map.put("message", "下载文件失败" + exception.getMessage());
                response.getWriter().println(JSON.toJSONString(map));
            }

        }
    }

}
